package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ThenCombineExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 第一个独立任务：获取用户基本信息
        CompletableFuture<String> userInfoFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("获取用户信息线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "User: John Doe";
        });

        // 第二个独立任务：获取用户订单信息
        CompletableFuture<String> orderInfoFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println("获取订单信息线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Order: #12345";
        });

        // thenCombine: 合并两个独立任务的结果
        CompletableFuture<String> combinedFuture = userInfoFuture.thenCombine(orderInfoFuture, (userInfo, orderInfo) -> {
            System.out.println("thenCombine执行线程: " + Thread.currentThread().getName());
            return userInfo + " | " + orderInfo;
        });

        System.out.println("合并结果: " + combinedFuture.get());
        System.out.println("主线程结束");
    }
}
